package com.limingfeiyu.platform.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.limingfeiyu.common.web.PageTable;
import com.limingfeiyu.platform.management.entity.SysDict;
import com.limingfeiyu.platform.management.mapper.SysDictMapper;
import com.limingfeiyu.platform.management.service.ISysDictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 系统字典 服务实现类
 * </p>
 *
 * @author 黎铭飞羽
 * @since 2024-03-02
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements ISysDictService {

	@Override
    public Page<SysDict> pageList(PageTable<SysDict> pageTable) {
        QueryWrapper<SysDict> userQw = new QueryWrapper<>();
        if (pageTable.getParam() != null) {
            userQw.lambda() ;
        }
        Page<SysDict> page = super.page(pageTable.getPage(), userQw);
        return page;
    }

    @Override
    public SysDict getSysDictByDictName(String dictName) {
        QueryWrapper<SysDict> sysDictQueryWrapper = new QueryWrapper<>();
        sysDictQueryWrapper.lambda().eq(SysDict::getDelFlag, 0).eq(SysDict::getDictName, dictName);
        return super.getOne(sysDictQueryWrapper);
    }

    @Override
    public List<SysDict> getContainChildrenDictList()  {
        SysDict sysDict = new SysDict();
        sysDict.setDictId(0);
        return getSysDictChildren(sysDict);

    }

    @Override
    public List<SysDict> getContainChildrenDictListByDictName(String dictName) {
        SysDict sysDictByDictName = getSysDictByDictName(dictName);
        return getSysDictChildren(sysDictByDictName);
    }



    // ------------- 私有的
    /**
     * 获取字典子项
     * @param sysDict
     * @return
     * @throws Exception
     */
    private List<SysDict> getSysDictChildren(SysDict sysDict)  {
        List<SysDict> sysDictList = getSysDictListByDictParentId(sysDict.getDictId());
        if (sysDictList == null || sysDictList.size() <= 0) {
            return null;
        }
        for (SysDict dict : sysDictList) {
            dict.setChildren(getSysDictChildren(dict));
        }
        return sysDictList;
    }

    /**
     * 根据上级ID获取系统字典列表
     * @param dictId
     * @return
     * @throws Exception
     */
    private List<SysDict> getSysDictListByDictParentId(Integer dictId)  {
        QueryWrapper<SysDict> sysDictQueryWrapper = new QueryWrapper<>();
        sysDictQueryWrapper.lambda().eq(SysDict::getDictParentId, dictId);
        return super.list(sysDictQueryWrapper);
    }
}
